const { app, BrowserWindow, ipcMain, dialog, Menu } = require('electron')
const path = require('path')

// 创建窗口
const createWindow = () => {
    const win = new BrowserWindow({
        title: '默认标题',
        width: 800,
        height: 600,
        show: false,
        minHeight: 300,
        minWidth: 400,
        // 禁止缩放
        // resizable:false,
        icon:'lg.ico',
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        }
    })


    const menu = Menu.buildFromTemplate([
        {
            label: app.name,
            submenu: [
                {
                    click: () => win.webContents.send('update-counter', 1),
                    label: 'Increment'
                },
                {
                    click: () => win.webContents.send('update-counter', -1),
                    label: 'Decrement'
                }
            ]
        }
    ])
    Menu.setApplicationMenu(menu)
    win.loadFile('index.html')
    // 当DOM加载完才显示窗口
    win.on('ready-to-show',()=>{
        win.show()
    })

    win.webContents.openDevTools()
}

function setTitle(event, title) {
    const webContent = event.sender
    const win = BrowserWindow.fromWebContents(webContent)
    win.setTitle(title)
}

async function handleFileOpen() {
    const { canceled, filePaths } = await dialog.showOpenDialog()
    if (!canceled) {
        return filePaths[0]
    }
}

function openNewWin(){
    new BrowserWindow({
        title: '新窗口',
        width: 300,
        height: 200
    })
}

app.whenReady().then(() => {
    // 单向通讯
    ipcMain.on('set-title', setTitle)
    // 双向通讯
    ipcMain.handle('dialog:openFile', handleFileOpen)
    // 主进程到渲染器进程
    ipcMain.on('counter-value', (_event, value) => {
        console.log(value)
    })

    ipcMain.on('newWin',openNewWin)
    createWindow()

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow()
        }
    })
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})